package com.sw.chinesewriteboard.copybook;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sw.chinesewriteboard.R;
import com.sw.chinesewriteboard.config.ChineseDataConfig;
import com.sw.chinesewriteboard.databinding.ActivityCopybookZhBinding;
import com.sw.chinesewriteboard.model.ChineseData;
import com.sw.chinesewriteboard.model.dialog.BrowserDialog;
import com.sw.chinesewriteboard.operation.CharacterOperation;
import com.sw.chinesewriteboard.operation.ChineseDataOperate;
import com.sw.chinesewriteboard.utils.BitmapUtils;
import com.sw.chinesewriteboard.utils.KeyBoardUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ZhCopybookActivity extends CopybookActivity {

    protected ActivityCopybookZhBinding binding;

    protected int mPage = 0; // 当前页数
    private final int PAGE_LENGTH = 1;    // 总页数
    protected Map<String, String> mCharacterMap;  // 汉字-拼音字典
    protected LinearLayout mWordPaper;
    protected LinearLayout mWordList;
    protected ChineseDataOperate mChineseDataOperate;
    protected int WRC = ViewGroup.LayoutParams.WRAP_CONTENT;

    protected ChineseData mData;
    protected List<String> mListContent = new ArrayList<>();
    private Bitmap resultBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCopybookZhBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        init();
        initOwnView();
        refreshCopyBookView();
    }

    protected abstract void initOwnView();

    public ChineseData getData() {
        return mData;
    }

    public List<String> getListContent() {
        return mListContent;
    }

    // 是否支持拼音
    protected abstract boolean isPinyinEnabled();

    // 是否需要加载拼音
    protected abstract boolean needInitDir();

    protected abstract ChineseDataOperate.ArrangeType setArrangeType();

    protected Bitmap loadBitmapFromView() {
        int w = ChineseDataConfig.getA4width(this);
        int h = ChineseDataConfig.getA4height(this);
        System.out.println("GGGG" + w);
        System.out.println("GGGG" + h);
        System.out.println("GGGG" + mWordList.getMeasuredWidth());
        System.out.println("GGGG" + mWordList.getMeasuredHeight());

        int mainPageWidth = binding.cbIvCopybook.getWidth();
        int mainPageHeight = binding.cbIvCopybook.getHeight();

        float scaleWidth = (float) mainPageWidth / w;
        float scaleHeight = (float) mainPageHeight / h;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        resultBitmap = bmp;
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /* 如果不设置canvas画布为白色，则生成透明 */
        mWordPaper.layout(0, 0, w, h);
        mWordPaper.draw(c);
        Bitmap resBmp = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);

        return resBmp;
    }

    /*
   加载其它部分
    */
    protected CharacterOperation mCharacterOperation;
    protected List<TextView> mEditTextList;

    private void init() {
        mEditTextList = new ArrayList<>();
        mCharacterOperation = new CharacterOperation(this);
        mCharacterMap = new HashMap<>();
        mData = new ChineseData(this);
        mChineseDataOperate = new ChineseDataOperate(this);


        binding.cbIvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveCopyBook();
            }
        });

        binding.cbIvCopybook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.vbnBottomNavigation.setContainerInvisible();
                KeyBoardUtils.hideKeyBoard(ZhCopybookActivity.this);
            }
        });

        if (needInitDir()) {
            try {
                InputStream is = this.getAssets().open("key.txt");
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = br.readLine()) != null) {
                    String[] temp = line.split(",");
                    mCharacterMap.put(temp[0], temp[1]);
                }
                br.close();
                is.close();
            } catch (IOException e) {
                System.out.println("日志：加载字典失败");
                e.printStackTrace();
            }
        }
    }

    private void saveCopyBook() {
        if (resultBitmap != null) {
            showLoadingDialog();
            if(!BitmapUtils.bitmap2Path(this, resultBitmap, SAVEDIR, picName)){
                hideLoadingDialog();
                toastUtils.show("图片保存失败~");
            } else{
                binding.vbnBottomNavigation.postDelayed(() -> {
                    hideLoadingDialog();
                    toastUtils.show("图片已成功保存到相册~");
                }, 1000);
            }
        } else {
            toastUtils.show("请先编辑字帖~");
        }
    }


    public void refreshCopyBookView() {

        int COLUMN_LENGTH = ChineseDataConfig.TOTAL_LENGTH_COLUMN;
        int ROW_LENGTH = ChineseDataConfig.TOTAL_LENGTH_ROW;

        mWordPaper = new LinearLayout(this);
        mWordPaper.setLayoutParams(new LinearLayout.LayoutParams(ChineseDataConfig.getA4width(this), ChineseDataConfig.getA4height(this)));
        mWordPaper.setGravity(Gravity.CENTER);
        mWordPaper.setAlpha(0f);
        binding.getRoot().addView(mWordPaper);

        mWordList = new LinearLayout(this);
        mWordList.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
        mWordList.setOrientation(LinearLayout.VERTICAL);
        mWordList.removeAllViews();

        mEditTextList.clear();

        mData.setText(mChineseDataOperate.listToString(setArrangeType(), mListContent));

        int startIndex = ChineseDataConfig.TOTAL_LENGTH * mPage;    // 字符串的起始坐标
        int k = startIndex;
        System.out.println("日志：p：" + mPage + "    k:" + k);
        for (int i = 0; i < ROW_LENGTH; i++) {
            LinearLayout row = new LinearLayout(this);
            row.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
            row.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < COLUMN_LENGTH; j++) {
                if (j == 0) {
                    mCharacterOperation.setIndex(mCharacterOperation.LEFTMOST);
                } else if (j == COLUMN_LENGTH - 1) {
                    mCharacterOperation.setIndex(mCharacterOperation.RIGHTMOST);
                } else {
                    mCharacterOperation.setIndex(mCharacterOperation.NORMAL);
                }
                View view = createCharacterLayout(mData.getText().charAt(k), mData);
                view.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
                row.addView(view);
                k++;
            }
            System.out.println("GGGG" + row.getWidth());
            mWordList.addView(row);
        }
        mWordPaper.addView(mWordList);

        binding.cbIvCopybook.post(new Runnable() {
            @Override
            public void run() {
                binding.cbIvCopybook.setImageBitmap(loadBitmapFromView());
                binding.getRoot().removeView(mWordPaper);
            }
        });
    }

    /*
    创建单个字符，带三线格
     */
    protected final int PINYIN_LENGTH_MAX_1 = 6;
    protected final float PINYIN_FONT_SIZE_MAX_1 = 26;
    protected final int PINYIN_LENGTH_MAX_2 = 5;
    protected final float PINYIN_FONT_SIZE_MAX_2 = 30;

    @SuppressLint("SetTextI18n")
    protected View createCharacterLayout(char c, ChineseData data) {
        int gridWidth = ChineseDataConfig.getGridWidth(ZhCopybookActivity.this);

        LinearLayout characterLayout = new LinearLayout(this);
        characterLayout.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
        characterLayout.setOrientation(LinearLayout.VERTICAL);

        final TextView character = new TextView(this);

        if (isPinyinEnabled()) {
            final TextView pinyin = new TextView(this);
            pinyin.setGravity(Gravity.CENTER);
            pinyin.setEnabled(true);

            characterLayout.addView(pinyin, new LinearLayout.LayoutParams(gridWidth, gridWidth * 4 / 7));

            mCharacterOperation.set3LinesAppearance(pinyin, data);
            String py = mCharacterMap.get("" + c);
            if (py != null) {
                pinyin.setText(py);
                if (py.length() == PINYIN_LENGTH_MAX_1) {
                    pinyin.setTextSize(PINYIN_FONT_SIZE_MAX_1);
                } else if (py.length() == PINYIN_LENGTH_MAX_2) {
                    pinyin.setTextSize(PINYIN_FONT_SIZE_MAX_2);
                }
            } else {
                pinyin.setText(" ");
            }

            pinyin.setCustomSelectionActionModeCallback(new ActionMode.Callback2() {
                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    MenuInflater menuInflater = mode.getMenuInflater();
                    menuInflater.inflate(R.menu.selection_action_menu, menu);
                    return true;//返回false则不会显示弹窗
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    //根据item的ID处理点击事件
                    if (item.getItemId() == R.id.search_pinyin) {
                        new BrowserDialog(ZhCopybookActivity.this).setCharacter(character.getText().toString()).show();
                        Toast.makeText(ZhCopybookActivity.this, "友情提示：长按复制拼音", Toast.LENGTH_SHORT).show();
                        mode.finish();//收起操作菜单
                    }
                    return false;//返回true则系统的"复制"、"搜索"之类的item将无效，只有自定义item有响应
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {

                }
            });
            mEditTextList.add(pinyin);
        }


        character.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams characterParams = new LinearLayout.LayoutParams(gridWidth, gridWidth);
        characterParams.bottomMargin = 30;
        character.setEnabled(false);
        character.setText("" + c);
        mCharacterOperation.setCharacterAppearance(character, data);
        mEditTextList.add(character);
        characterLayout.addView(character, characterParams);

        return characterLayout;
    }
}
